import {
  login,
  logout,
  getRole
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter,
  asyncRoutes,
  constantRoutes,
  anyRoutes
} from '@/router'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    // 路由权限
    routes: [],
    // 角色
    role: '',
    // 根据用户权限要展示的异步路由
    resultAsyncRoutes: [],
    // 要展示的所有路由
    resultAllRoutes: [],
    isAddRoutes: false
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 存储用户信息
  SET_USERINFO: (state, res) => {
    // 路由权限
    state.routes = res.data;
    // 角色
    state.role = res.role;
  },
  // 根据用户权限要展示的异步路由
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {
    // 储存当前用户的异步路由
    state.resultAsyncRoutes = asyncRoutes;
    // 合并要展示的所有的路由
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes);
    // 给路由器添加新的路由
    router.addRoutes(state.resultAllRoutes);
    state.isAddRoutes = true;
  }
}
// 过滤出要展示的路由
const computeRouting = (asyncRoutes, routes) => {

  return asyncRoutes.filter(item => {
    if (routes.indexOf(item.name) != -1) {
      // 使用递归过滤子路由
      if (item.children && item.children.length) {
        item.children = computeRouting(item.children, routes);
      }
      return true;
    }
  })
}

const actions = {
  // 登录
  login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password
      }).then(response => {
        const {
          data
        } = response
        // 储存token
        commit('SET_TOKEN', response.token)
        // 在本地储存用户的id
        window.localStorage.setItem("userId", data.userId)
        window.localStorage.setItem("username", data.username)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户权限
  async getInfo({
    commit,
    state
  }) {
    let res = await getRole();
    if (res.status == 0) {
      //vuex存储用户权限
      commit('SET_USERINFO', res);
      // 根据用户权限要展示的异步路由
      commit('SET_RESULTASYNCROUTES', computeRouting(asyncRoutes, res.data));
    }
  },
  // 退出
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        // 退出移除用户ID
        window.localStorage.removeItem('userId')
        window.localStorage.removeItem('username')
        // 重置路由
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
